<?php

namespace App\Exception;

use App\Util\ResultUtil;
use Elite\Infrastructure\Exception\DumpDieException;
use Elite\Infrastructure\Helper\Logger;
use Elite\Infrastructure\Server\Task\Tasker;
use Swoole\Server\Task;
use Throwable;

class TaskExceptionHandler {

    /**
     * @var Logger
     */
    private $logger;

    /**
     * @var Tasker
     */
    private $tasker;

    /**
     * @var Task
     */
    private $task;


    public function __construct(Tasker $tasker, Task $task) {
        $this->logger = logger('exception_' . date("Y-m-d") . '.log');
        $this->tasker = $tasker;
        $this->task = $task;
    }

    public function handle(Throwable $throwable) {
        if ($throwable instanceof DumpDieException) {
            var_dump($throwable->getMessage());
            return;
        }

        $this->tasker->setData(ResultUtil::fail($throwable->getMessage()));
        $this->task->finish($this->tasker);

        $this->writeExceptionLog($throwable);

        // 其他错误开发环境打印异常
        if ((config('env') === 'DEV')) {
            var_dump($throwable->getMessage());
        }
    }

    private function writeExceptionLog(Throwable $throwable) {
        $errorList[] = "{$throwable->getMessage()} In {$throwable->getFile()} Line {$throwable->getLine()}";
        $errorList[] = "Call Stack:";
        $errorList[] = $throwable->getTraceAsString();
        $stack = implode("\r\n", $errorList);
        if ((config('env') === 'DEV')) {
            var_dump($stack);
        }
        $this->logger->error($stack);
    }

}